package com.ruoyi.common.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

public class EasyExcelUtil {

    /**
     * 使用模板导出Excel
     * @param response HttpServletResponse
     * @param data 要导出的数据
     * @param templateFileName 模板文件名(放在resources/excel目录下)
     * @param fileName 导出的文件名
     */
    public static void exportWithTemplate(HttpServletResponse response,
                                          List<?> data,
                                          String templateFileName,
                                          String fileName) {
        try {
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 获取模板文件流
            InputStream templateStream = EasyExcelUtil.class.getClassLoader()
                    .getResourceAsStream("excel/" + templateFileName);

            // 设置样式策略
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            headWriteCellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                    new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

            // 写入Excel
            EasyExcel.write(response.getOutputStream())
                    .withTemplate(templateStream)
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .sheet()
                    .doFill(data);

        } catch (IOException e) {
            throw new RuntimeException("导出Excel失败", e);
        }
    }

    /**
     * 使用模板和多个数据源导出Excel
     * @param response HttpServletResponse
     * @param dataMap 多个数据源的Map
     * @param templateFileName 模板文件名
     * @param fileName 导出的文件名
     */
    public static void exportWithTemplate(HttpServletResponse response,
                                          Map<String, Object> dataMap,
                                          String templateFileName,
                                          String fileName) {
        try {
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 获取模板文件流
            InputStream templateStream = EasyExcelUtil.class.getClassLoader()
                    .getResourceAsStream("excel/" + templateFileName);

            // 写入Excel
//            EasyExcel.write(response.getOutputStream())
//                    .withTemplate(templateStream)
//                    .sheet()
//                    .doFill(dataMap);


            //官方用法
            ExcelWriter excelWriter = null;
            try {
                excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(templateStream).build();
                WriteSheet writeSheet = EasyExcel.writerSheet().build();
                FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
                List<Object> list= (List<Object>) dataMap.get("list");
                excelWriter.fill(list,fillConfig, writeSheet);
                excelWriter.fill(dataMap, writeSheet);
            } finally {
                // 千万别忘记关闭流
                if (excelWriter != null) {
                    excelWriter.finish();
                }
            }

        } catch (IOException e) {
            throw new RuntimeException("导出Excel失败", e);
        }
    }
}
